<template>
  <div class="onlyoffice-container" v-loading="loading">
    <!-- <div @click="ceshi()">测试文件</div> -->
    <div class="d-f template-edit-container">
      <div
        class="editor-container-class"
        id="editor-container"
        ref="editorContainer"
      ></div>
      <div
        class="bookmark-list"
        :class="{ 'bookmark-list-width': isCollapsed }"
      >
        <div class="table-container">
          <div class="toggle-button" @click="bookmarkListShow()">
            <el-icon :size="20">
              <component
                :is="isCollapsed ? 'ArrowRightBold' : 'ArrowLeftBold'"
              />
            </el-icon>
          </div>
          <el-table
            :data="tableData"
            style="width: 100%"
            highlight-current-row
            border
            stripe
            @row-click="accBookmarks"
            :header-cell-style="{
              'background-color': '#f5f7fa',
              'font-weight': 'bold',
            }"
          >
            <el-table-column
              prop="id"
              label="序号"
              width="80"
              align="center"
              header-align="center"
            />
            <el-table-column
              prop="resName"
              show-overflow-tooltip
              label="资源名称"
              align="center"
            />
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button
                  size="small"
                  v-if="scope.row.dynamic == 1"
                  type="primary"
                  @click="handleSetting(scope.row)"
                  ><el-icon><Setting /></el-icon
                ></el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index)"
                  ><el-icon><Delete /></el-icon
                ></el-button>
              </template>
            </el-table-column>

            <!-- 底部按钮行 -->
            <template #append>
              <div class="table-footer">
                <el-button
                  type="primary"
                  @click="handleAddResource"
                  size="small"
                >
                  <el-icon><Plus /></el-icon>添加资源
                </el-button>
                <el-button
                  type="success"
                  @click="handleUpdateDocument"
                  size="small"
                >
                  <el-icon><Refresh /></el-icon>更新文档
                </el-button>
              </div>
            </template>
          </el-table>
        </div>
      </div>
    </div>
    <BaseDialog
      v-model="showFormDialog"
      title="表单弹窗"
      :before-close="handleBeforeClose"
      @confirm="submitForm"
    >
      <linkResourcesView
        v-model="resId"
        :options="accbookmarks"
        @change="linkResourceschange"
        placeholder="请选择资源"
      ></linkResourcesView>
    </BaseDialog>
    <BaseDialog
      v-model="showDynamiscs"
      title="表单弹窗"
      :before-close="handleBeforeClose"
      @confirm="resSubmitForm"
    >
      <dynamicsNat
        ref="dynamicsNatRef"
        v-if="showDynamiscs"
        :id="dynamicsNatId"
        :docId="documentId"
      ></dynamicsNat>
      <el-form-item label="资源内容" prop="resText" style="height: 100%">
        <Tinymce
          v-model="resText"
          :disabled="form.dynamic != 1"
          :id="dynamicsNatId"
        />
      </el-form-item>
    </BaseDialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Plus, Refresh, Setting, Delete } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import {
  resourceinfo,
  resourceinfopage,
  resourceinfoRemove,
} from "@/api/naturalRes";
import linkResourcesView from "./linkResources.vue";
import Tinymce from "../naturalRes/Tinymce.vue";
import dynamicsNat from "../naturalRes/dynamicsNat.vue";
import {
  documentinfopage,
  documentInfoRemove,
  documentResourceSelect,
  documentResourceSave,
  documentResourceDelete,
} from "@/api/office";

const dynamicsNatRef = ref(null);
const editorReady = ref(false);
const bookmarkListWidth = ref();
const isCollapsed = ref(false);
const statusMessage = ref("");
const editorContainer = ref(null);
const route = useRoute();
let docEditor = null;
let currentFile = null;
const bookmarkName = ref("");
const form = ref({
  username: "",
  password: "",
});

const loading = ref(true);
//资源id
const resId = ref("");
const resName = ref("");

//书签列表
const tableData = ref();
const accbookmarks = ref();

//富文本展示
const resText = ref();

const dynamicsNatId = ref();
const documentId = ref(route.query.id);

const ceshi = () => {
  docEditor.refreshFile(); // 或 docEditor.forceSave();
};

const accBookmarksurl = ref("");
// 当前选中的索引
const selectedIndex = ref(null);
let config;
// 计算当前选中的书签
const selectedBookmark = computed(() => {
  return selectedIndex.value !== null
    ? tableData.value[selectedIndex.value]
    : null;
});

const bookmarkListShow = () => {
  isCollapsed.value = !isCollapsed.value;
};

const handleDelete = (row) => {
  Asc.scope.resID = row.resId;

  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      window.connector.callCommand(function () {
        let doc = Api.GetDocument();
        const bookmark = doc.GetBookmark(Asc.scope.resID);
        const oRange = bookmark.GetRange();
        //删除书签
        oRange.Delete();
        bookmark.Delete();
      });
      await documentResourceDelete({
        documentId: route.query.id,
        resId: Asc.scope.resID,
      });
      documentResourceChange();
    })
    .catch(() => {});
};

const linkResourceschange = (resId) => {
  const selectedOption = accbookmarks.value.find(
    (item) => item.resId === resId
  );
  resName.value = selectedOption.resName;
};

// 选择书签的方法
const selectBookmark = (bookmark, index) => {
  selectedIndex.value = index;
};

const accBookmarks = (selectedBookmark) => {
  Asc.scope.resID = selectedBookmark.resId;
  Asc.scope.text = selectedBookmark.resName;
  window.connector.callCommand(function () {
    let doc = Api.GetDocument();
    const bookmark = doc.GetBookmark(Asc.scope.resID);
    //定位书签
    bookmark.Select();
  });
};

// 初始化编辑器
const initEditor = (config) => {
  console.log("初始化编辑器", window.DocsAPI, config);

  if (window.docEditor) {
    window.docEditor.destroyEditor();
  }
  console.log("初始化编辑器", window.DocsAPI, config);

  docEditor = new window.DocsAPI.DocEditor("editor-container", config);
  console.log("docEditor", docEditor);

  window.docEditor = docEditor;
  // 监听编辑器就绪事件
  window.addEventListener("message", (e) => {
    if (e.data === "ready") {
      editorReady.value = true;
      statusMessage.value = `已加载: ${config.document.title}`;
    }
  });
};

const documentResourceChange = async () => {
  const data = await documentResourceSelect(route.query.id);
  tableData.value = data;
};
const queryData = ref({
  pageNum: 1,
  pageSize: 10,
  orderBy: "createTime",
  conditions: [
    {
      column: "",
      type: "",
      value: {},
    },
  ],
  asc: false,
});
const accResources = async () => {
  const data = await resourceinfopage(queryData.value);
  console.log("data", data);

  accbookmarks.value = data.records;
};
accResources();
documentResourceChange();
var onDocumentReady = function () {
  window.connector = docEditor.createConnector();
};

var onDocumentStateChange = function (event) {
  var title = document.title.replace(/\*$/g, "");
  document.title = title + (event.data ? "*" : "");
};
const getCurrentSelection = () => {
  return new Promise((resolve) => {
    docEditor.getApi((api) => {
      if (api) {
        const selection = api.getSelection();
        resolve(selection);
      } else {
        resolve(null);
      }
    });
  });
};
// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  currentFile = file;
  statusMessage.value = `正在加载: ${file.name}`;
  editorReady.value = false;

  loadViaBase64(file);
};
// Base64方式加载（适合小文件）
const loadViaBase64 = (file = null) => {
  // const reader = new FileReader();
  // reader.onload = (e) => {
  // const fileType = getOnlyOfficeFileType(fileExtension);

  config = {
    documentType: "word",
    document: {
      title: "通用模板.docx",
      url: route.query.fileUrl,
      // key: route.query.id,
      key: Date.now().toString(36) + Math.random().toString(36).substr(2, 5),
      fileType: "docx",
    },
    forcesavetype: 1,
    editorConfig: {
      customization: {
        // compactToolbar: true,
        forcesave: true,
        autosave: false, // 启用自动保存
        // autosaveInterval: 5, // 每 30 秒保存一次（即使未修改）
        // toolbarNoTabs: true,
        // help: false,
        // compactHeader: true,
        // hideRightMenu: true,
      },
      // coEditing: {
      //   mode: "fast",
      //   change: true,
      // },
      // recent: [
      //   {
      //     folder: "Example Files",
      //     title: "exampledocument1.docx",
      //     url: route.query.fileUrl,
      //   },
      // ],
      mode: route.query.mode,
      callbackUrl:
        "http://10.222.125.103:18086/document/callback/" + route.query.id,
      lang: "zh-CN",
      // user: {
      //   name: "当前用户",
      //   id: "103",
      // },
    },
    events: {
      onDocumentReady: onDocumentReady,
      onDocumentStateChange,
      onRequestRefreshFile,
      onSubmit,
      onOutdatedVersion: function (event) {
        console.log("文档已触发保存（前端通知）", event);
        // 这里可以通知你的前端：OnlyOffice 已尝试保存
        // 但此时 callbackUrl 可能还未被服务器调用
      },
      onDownload: function (event) {
        console.log("下载事件触发", event);
        if (event.data && event.data.url) {
          // 这里处理实际文档内容获取
          fetch(event.data.url)
            .then((response) => response.blob())
            .then((blob) => {
              console.log("成功获取文档内容");
              // 处理blob对象...
            });
        }
      },
    },
  };
  setTimeout(() => {
    initEditor(config);
    loading.value = false;
  }, 4000);
};

const onRequestRefreshFile = () => {
  console.log("123567");

  docEditor.refreshFile({
    document: {
      fileType: "docx",
      key: Date.now().toString(36) + Math.random().toString(36).substr(2, 5),
      title: "Example Document Title.docx",
      url: route.query.fileUrl,
    },
    documentType: "word",
    editorConfig: {
      callbackUrl:
        "http://10.222.125.103:18086/document/callback/" + route.query.id,
    },
    token:
      "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb2N1bWVudCI6eyJmaWxlVHlwZSI6ImRvY3giLCJrZXkiOiJLaGlyejZ6VFBkZmQ3IiwidGl0bGUiOiJFeGFtcGxlIERvY3VtZW50IFRpdGxlLmRvY3giLCJ1cmwiOiJodHRwczovL2V4YW1wbGUuY29tL3VybC10by1leGFtcGxlLWRvY3VtZW50LmRvY3gifSwiZG9jdW1lbnRUeXBlIjoid29yZCIsImVkaXRvckNvbmZpZyI6eyJjYWxsYmFja1VybCI6Imh0dHBzOi8vZXhhbXBsZS5jb20vdXJsLXRvLWNhbGxiYWNrLmFzaHgifX0.vbezS2aM8Xf8qFzIAsO-jrIsi7VLxjRYkIkwh5jLTJU",
  });
};

const onSubmit = () => {
  console.log("123456");
};

// 获取文件扩展名
const getFileExtension = (filename) => {
  return filename.split(".").pop().toLowerCase();
};

// 获取OnlyOffice文件类型
const getOnlyOfficeFileType = (extension) => {
  const textTypes = ["docx", "doc", "odt", "rtf", "txt"];
  const spreadsheetTypes = ["xlsx", "xls", "ods", "csv"];
  const presentationTypes = ["pptx", "ppt", "odp"];

  if (textTypes.includes(extension)) return "text";
  if (spreadsheetTypes.includes(extension)) return "spreadsheet";
  if (presentationTypes.includes(extension)) return "presentation";
  return "text";
};

// 获取MIME类型
const getMimeType = (extension) => {
  const types = {
    docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    doc: "application/msword",
    xls: "application/vnd.ms-excel",
    ppt: "application/vnd.ms-powerpoint",
    odt: "application/vnd.oasis.opendocument.text",
    ods: "application/vnd.oasis.opendocument.spreadsheet",
    odp: "application/vnd.oasis.opendocument.presentation",
    rtf: "application/rtf",
    txt: "text/plain",
  };

  return types[extension] || "application/octet-stream";
};

//弹窗
const showFormDialog = ref(false);
const showDynamiscs = ref(false);
const handleAddResource = async () => {
  showFormDialog.value = true;
};
const handleSetting = async (row) => {
  const data = await resourceinfo(row.resId);
  resText.value = data.resText;
  dynamicsNatId.value = row.resId;
  showDynamiscs.value = true;
};
const resSubmitForm = async () => {
  console.log("dynamicsNatRef.value", dynamicsNatRef.value);

  if (dynamicsNatRef.value) {
    const tableData = await dynamicsNatRef.value.saveData();
  }
  showDynamiscs.value = false;
};
//更新文档
const handleUpdateDocument = () => {
  config.document.key =
    Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
  initEditor(config);
};

const handleBeforeClose = (done) => {};

const submitForm = async () => {
  showFormDialog.value = false;
  console.log("resName", resName.value);

  Asc.scope.resID = resId.value;
  Asc.scope.text = resName.value;
  window.connector.callCommand(function () {
    let doc = Api.GetDocument();
    let range1 = doc.GetRange(
      doc.GetRangeBySelect().Start,
      doc.GetRangeBySelect().End
    );
    console.log("range1", Asc.scope.resID);

    //插入书签
    range1.AddBookmark(Asc.scope.resID);
    const bookmark = doc.GetBookmark(Asc.scope.resID);
    console.log("Asc.scope.text", Asc.scope.text);

    bookmark.SetText(Asc.scope.text);
  });
  await documentResourceSave({
    documentId: route.query.id,
    resId: resId.value,
  });
  documentResourceChange();
};

// 组件挂载时加载OnlyOffice API
onMounted(() => {});
loadViaBase64();

// 组件卸载前清理
onBeforeUnmount(() => {
  if (docEditor) {
    docEditor.destroyEditor();
  }
});
</script>

<style lang="scss" scoped>
.onlyoffice-container {
  width: 100%;
  height: 800px;
  display: flex;
  min-height: 800px !important;
  flex-direction: column;
}

#editor-container {
  width: 100%;
  height: 800px;
  border: 1px solid #ddd;
}

.status {
  margin-left: 10px;
  color: #666;
}

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.template-edit-container {
  height: 780px;
}

/* 书签列表 */
.bookmark-list {
  margin: 0 auto;
  width: 20px;
  margin-left: 20px;
  font-family: Arial, sans-serif;
  position: relative;
  transition: all 0.3s ease;

  .toggle-button {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #ffffff;
    border: 1px solid #dcdfe6;
    border-radius: 4px 0 0 4px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    margin-right: -1px; /* 与表格边框重叠 */
    z-index: 1;
    color: #606266;
  }

  .toggle-button:hover {
    background-color: #f5f7fa;
    color: #409eff;
    border-color: #c6e2ff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
    transform: translateX(-1px);
  }

  .toggle-button:active {
    transform: translateX(-1px) scale(0.98);
  }

  ul {
    list-style: none;
    padding: 0;
    margin: 20px 0;
  }

  li {
    padding: 10px 15px;
    margin-bottom: 5px;
    background-color: #f5f5f5;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;
  }

  li:hover {
    background-color: #e9e9e9;
  }

  li.active {
    background-color: #42b983;
    color: white;
    font-weight: bold;
  }

  .bookmark-content {
    padding: 15px;
    border: 1px solid #eee;
    border-radius: 4px;
    margin-top: 20px;
  }

  .bookmark-content h3 {
    margin-top: 0;
    color: #42b983;
  }

  .bookmark-content a {
    display: inline-block;
    margin-top: 10px;
    color: #42b983;
    text-decoration: none;
  }

  .bookmark-content a:hover {
    text-decoration: underline;
  }

  .link-resources {
    position: absolute;
    bottom: 20px;
    right: 20px;
    background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
    color: white;
    padding: 12px 24px;
    border: none;
    border-radius: 30px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
    transition: all 0.3s ease;
  }
  .link-resources:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
  }
}

.bookmark-list-width {
  width: 700px;
}

.table-container {
  padding: 20px;
  background-color: #fff;
  padding-left: 40px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  .toggle-button {
    position: absolute;
    left: 5px;
  }
}

.table-footer {
  padding: 12px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  background-color: #fafafa;
  border-top: 1px solid #ebeef5;
}

.el-table {
  margin-top: 20px;
  transition: opacity 0.2s ease;
}

/* 按钮悬停效果增强 */
.table-footer .el-button {
  transition: all 0.2s ease;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}

.el-table ::v-deep .el-table__append-wrapper {
  border-top: 1px solid #ebeef5;
}

/* 斑马纹表格行动画 */
.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
  transition: background-color 0.3s ease;
}

.el-table__row:hover td {
  background-color: #f0f7ff !important;
  transition: background-color 0.2s ease;
}
</style>
